<template>
  <div class="app-container">
    <!-- Tab切换 -->
    <el-tabs v-model="activeName" type="card" @tab-click="handleTabClick">
      <!-- Tab 1: 志愿申请 -->
      <el-tab-pane label="志愿申请" name="application">
        <template slot="label">
          <span><i class="el-icon-document"></i> 志愿申请</span>
        </template>

        <!-- 统计卡片 -->
        <el-row :gutter="20" class="stats-row">
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-content">
                <i class="el-icon-document stats-icon" style="color: #409EFF;"></i>
                <div class="stats-text">
                  <div class="stats-value">{{ total }}</div>
                  <div class="stats-label">申请总数</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card" @click.native="filterByStatus('待审核')">
              <div class="stats-content">
                <i class="el-icon-time stats-icon" style="color: #E6A23C;"></i>
                <div class="stats-text">
                  <div class="stats-value">{{ pendingCount }}</div>
                  <div class="stats-label">待审核</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card" @click.native="filterByStatus('已录取')">
              <div class="stats-content">
                <i class="el-icon-check stats-icon" style="color: #67C23A;"></i>
                <div class="stats-text">
                  <div class="stats-value">{{ acceptedCount }}</div>
                  <div class="stats-label">已录取</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card" @click.native="filterByStatus('已拒绝')">
              <div class="stats-content">
                <i class="el-icon-close stats-icon" style="color: #F56C6C;"></i>
                <div class="stats-text">
                  <div class="stats-value">{{ rejectedCount }}</div>
                  <div class="stats-label">已拒绝</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 志愿优先级说明 -->
        <el-alert
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom: 20px;"
        >
          <template slot="title">
            <strong>💡 志愿优先级说明</strong>
          </template>
          <div style="font-size: 13px; line-height: 1.8; color: #606266;">
            • <strong style="color: #F56C6C;">第一志愿</strong>：学生将您作为首选导师，通常对您的方向有较强意向<br/>
            • <strong style="color: #E6A23C;">第二志愿</strong>：学生也很认可您的研究方向<br/>
            • <strong>审核建议</strong>：志愿仅代表学生意愿，您可根据学生综合情况（绩点、技术栈、个人简介等）自主决定是否录取<br/>
            • <strong>录取后</strong>：一旦您录取该学生，系统将自动使该学生的其他志愿失效
          </div>
        </el-alert>

        <!-- 搜索和操作栏 -->
        <el-card shadow="never" class="search-card">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
            <el-form-item label="学生姓名" prop="studentName">
              <el-input
                v-model="queryParams.studentName"
                placeholder="请输入学生姓名"
                clearable
                style="width: 200px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="申请状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 150px">
                <el-option label="待审核" value="待审核" />
                <el-option label="已录取" value="已录取" />
                <el-option label="已拒绝" value="已拒绝" />
                <el-option label="已取消" value="已取消" />
                <el-option label="已失效" value="已失效" />
              </el-select>
            </el-form-item>
            <el-form-item label="志愿优先级" prop="priority">
              <el-select v-model="queryParams.priority" placeholder="全部" clearable style="width: 150px">
                <el-option label="第一志愿" :value="1" />
                <el-option label="第二志愿" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 申请列表 -->
        <el-card shadow="never">
          <div slot="header" class="clearfix">
            <span class="card-title">志愿申请列表</span>
            <el-button
              style="float: right"
              type="success"
              icon="el-icon-view"
              size="small"
              @click="goToAcceptedStudents"
            >
              查看已录取学生
            </el-button>
          </div>

          <el-table v-loading="loading" :data="applicationList" border>
            <el-table-column label="序号" type="index" width="50" align="center" />
            
            <el-table-column label="学生信息" min-width="150">
              <template slot-scope="scope">
                <div><strong>{{ scope.row.studentName }}</strong></div>
                <div style="color: #909399; font-size: 12px;">{{ scope.row.studentNo }}</div>
              </template>
            </el-table-column>
            
            <el-table-column label="专业班级" min-width="150">
              <template slot-scope="scope">
                <div>{{ scope.row.major }}</div>
                <div style="color: #909399; font-size: 12px;">{{ scope.row.className }}</div>
              </template>
            </el-table-column>
            
            <el-table-column label="绩点" width="80" align="center">
              <template slot-scope="scope">
                <el-tag :type="getGpaType(scope.row.gpa)" size="small">
                  {{ scope.row.gpa || '-' }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column label="题目" min-width="180" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.topicTitle }}
              </template>
            </el-table-column>
            
            <el-table-column label="志愿" width="100" align="center">
              <template slot-scope="scope">
                <el-tag :type="scope.row.priority === 1 ? 'danger' : 'warning'" size="small">
                  <i :class="scope.row.priority === 1 ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
                  {{ scope.row.priority === 1 ? '第一志愿' : '第二志愿' }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column label="状态" width="100" align="center">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.status)" size="small">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column label="申请时间" align="center" width="160">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" align="center" width="200" fixed="right">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="handleView(scope.row)"
                >详情</el-button>
                <el-button
                  v-if="scope.row.status === '待审核'"
                  size="mini"
                  type="text"
                  icon="el-icon-check"
                  @click="handleAccept(scope.row)"
                  style="color: #67C23A;"
                >录取</el-button>
                <el-button
                  v-if="scope.row.status === '待审核'"
                  size="mini"
                  type="text"
                  icon="el-icon-close"
                  @click="handleReject(scope.row)"
                  style="color: #F56C6C;"
                >拒绝</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-card>

        <!-- 申请详情对话框 -->
        <application-detail 
          ref="applicationDetail" 
          @accept="handleAcceptFromDetail"
          @reject="handleRejectFromDetail"
        />

        <!-- 拒绝对话框 -->
        <reject-dialog ref="rejectDialog" @success="getList" />
      </el-tab-pane>

      <!-- Tab 2: 变更申请 -->
      <el-tab-pane label="变更申请" name="changeRequest">
        <template slot="label">
          <span>
            <i class="el-icon-refresh-right"></i> 变更申请
            <el-badge v-if="changeRequestPendingCount > 0" :value="changeRequestPendingCount" class="item" style="margin-left: 5px;" />
          </span>
        </template>
        
        <!-- 变更申请列表组件 -->
        <change-request-list ref="changeRequestList" @updateBadge="updateChangeRequestBadge" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { listTeacherApplications, acceptStudent } from "@/api/system/application";
import { listPendingChangeRequests } from "@/api/system/topicChangeRequest";
import ApplicationDetail from "./ApplicationDetail";
import RejectDialog from "./RejectDialog";
import ChangeRequestList from "@/views/system/topic-change/teacher/ChangeRequestList";

export default {
  name: "TeacherApplications",
  components: {
    ApplicationDetail,
    RejectDialog,
    ChangeRequestList
  },
  data() {
    return {
      // 当前激活的tab
      activeName: 'application',
      // 变更申请待审核数量（用于Badge）
      changeRequestPendingCount: 0,
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 申请列表
      applicationList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentName: null,
        status: null,
        priority: null
      }
    };
  },
  computed: {
    pendingCount() {
      return this.applicationList.filter(app => app.status === '待审核').length;
    },
    acceptedCount() {
      return this.applicationList.filter(app => app.status === '已录取').length;
    },
    rejectedCount() {
      return this.applicationList.filter(app => app.status === '已拒绝').length;
    }
  },
  created() {
    this.getList();
    this.getChangeRequestPendingCount();
  },
  methods: {
    /** Tab切换 */
    handleTabClick(tab) {
      if (tab.name === 'changeRequest') {
        // 切换到变更申请Tab时，刷新列表
        this.$refs.changeRequestList && this.$refs.changeRequestList.getList();
      }
    },
    /** 获取变更申请待审核数量 */
    getChangeRequestPendingCount() {
      listPendingChangeRequests({ pageNum: 1, pageSize: 999 }).then(response => {
        // 统计需要我审核的申请数量
        const list = response.rows || [];
        this.changeRequestPendingCount = list.filter(req => {
          // 这里需要根据实际情况判断是否需要当前教师审核
          // 简化处理，可以在后端返回一个字段标识
          return req.status === '待审核';
        }).length;
      });
    },
    /** 更新变更申请Badge */
    updateChangeRequestBadge(count) {
      this.changeRequestPendingCount = count;
    },
    /** 查询申请列表 */
    getList() {
      this.loading = true;
      listTeacherApplications(this.queryParams).then(response => {
        this.applicationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 按状态筛选 */
    filterByStatus(status) {
      this.queryParams.status = status;
      this.handleQuery();
    },
    /** 查看详情 */
    handleView(row) {
      this.$refs.applicationDetail.openDialog(row.applicationId);
    },
    /** 录取（从列表） */
    handleAccept(row) {
      const priorityText = row.priority === 1 ? '第一志愿' : '第二志愿';
      
      this.$confirm(
        `是否确认录取学生"${row.studentName}"？<br/><span style="color: #E6A23C;">（该学生将您作为${priorityText}）</span>`,
        '录取确认', 
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        return acceptStudent(row.applicationId);
      }).then(() => {
        this.$modal.msgSuccess("录取成功");
        this.getList();
      }).catch(() => {});
    },
    /** 录取（从详情对话框） */
    handleAcceptFromDetail(application) {
      const priorityText = application.priority === 1 ? '第一志愿' : '第二志愿';
      
      this.$confirm(
        `是否确认录取学生"${application.studentName}"？<br/><span style="color: #E6A23C;">（该学生将您作为${priorityText}）</span>`,
        '录取确认',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        return acceptStudent(application.applicationId);
      }).then(() => {
        this.$modal.msgSuccess("录取成功");
        this.getList();
      }).catch(() => {});
    },
    /** 拒绝（从列表） */
    handleReject(row) {
      this.$refs.rejectDialog.open(row);
    },
    /** 拒绝（从详情对话框） */
    handleRejectFromDetail(application) {
      this.$refs.rejectDialog.open(application);
    },
    /** 跳转到已录取学生页面 */
    goToAcceptedStudents() {
      this.$router.push('/system/application/teacher/accepted');
    },
    /** 绩点标签类型 */
    getGpaType(gpa) {
      if (!gpa) return 'info';
      if (gpa >= 3.5) return 'success';
      if (gpa >= 3.0) return '';
      if (gpa >= 2.5) return 'warning';
      return 'danger';
    },
    /** 状态标签类型 */
    getStatusType(status) {
      const map = {
        '待审核': 'warning',
        '已录取': 'success',
        '已拒绝': 'danger',
        '已取消': 'info',
        '已失效': 'info'
      };
      return map[status] || 'info';
    }
  }
};
</script>

<style scoped lang="scss">
.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-5px);
  }
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stats-icon {
  font-size: 48px;
  margin-right: 20px;
}

.stats-text {
  flex: 1;
}

.stats-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.search-card {
  margin-bottom: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
}

::v-deep .el-tabs__header {
  margin-bottom: 20px;
}

::v-deep .el-tabs__item {
  font-size: 15px;
  font-weight: 500;
}
</style>